package org.mikhaylov.cp.web.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.mikhaylov.cp.service.command.ServiceCommandContainer;
import org.mikhaylov.cp.service.response.Response;
import org.mikhaylov.cp.service.response.ResponseType;
import org.mikhaylov.cp.web.command.WebCommand;
import org.mikhaylov.cp.web.storage.Path;

public class UpdateProfileWebCommand extends WebCommand {

	private static final long serialVersionUID = 7491254745763783828L;
	private Logger log = Logger.getLogger(UpdateProfileWebCommand.class);

	private String name = null;
	private String phone = null;
	private String desc = null;
	private String city = null;
	
	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getParameter("name") == null || request.getParameter("phone") == null
				|| request.getParameter("desc") == null
				|| request.getParameter("city") == null
				|| request.getParameter("city").isEmpty()) {
			System.out.println(request.getParameter("name"));
			System.out.println(request.getParameter("phone"));
			System.out.println(request.getParameter("desc"));
			System.out.println(request.getParameter("city"));
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", "Wrong parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		name = request.getParameter("name");
		phone = request.getParameter("phone");
		desc = request.getParameter("desc");
		city = request.getParameter("city");
		
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		request.setAttribute("name", name);
		request.setAttribute("phone", phone);
		request.setAttribute("desc", desc);
		request.setAttribute("city", city);
		request.setAttribute("user", request.getSession().getAttribute("user"));
		Response r = ServiceCommandContainer.get("updateProfile").execute(request, null);
		if (r.getType() == ResponseType.ERROR) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", r.getMeta());
			log.debug(r.getMeta());
			return;
		}
		forward = Path.PAGE_PRG;
		request.setAttribute("next", Path.COMMAND_R_PROFILE);
		request.getSession().setAttribute("user", request.getAttribute("user"));
		
	}

}
